<HTML>
<HEAD>
<TITLE>[Chapter 14] And Then There Were Applets</TITLE>
<META NAME="author" CONTENT="John Zukowski">
<META NAME="date" CONTENT="Thu Jul 31 14:53:49 1997">
<META NAME="form" CONTENT="html">
<META NAME="metadata" CONTENT="dublincore.0.1">
<META NAME="objecttype" CONTENT="book part">
<META NAME="otheragent" CONTENT="gmat dbtohtml">
<META NAME="publisher" CONTENT="O'Reilly &amp; Associates, Inc.">
<META NAME="source" CONTENT="SGML">
<META NAME="subject" CONTENT="Java AWT">
<META NAME="title" CONTENT="Java AWT">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
</HEAD>
<body vlink="#551a8b" alink="#ff0000" text="#000000" bgcolor="#FFFFFF" link="#0000ee">

<DIV CLASS=htmlnav>
<H1><a href='index.htm'><IMG SRC="gifs/smbanner.gif"
     ALT="Java AWT" border=0></a></H1>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch13_03.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><B><FONT FACE="ARIEL,HELVETICA,HELV,SANSERIF" SIZE="-1">Chapter 14</FONT></B></TD>
<td width=172 align=right valign=top><A HREF="ch14_02.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
</table>

&nbsp;
<hr align=left width=515>
</DIV>
<H1 CLASS=chapter><A CLASS="TITLE" NAME="JAWT-CH-14">14. And Then There Were Applets</A></H1>

<DIV CLASS=htmltoc>

<p>
<b>Contents:</b><br>
What's a Java Applet?<br>
<A HREF="ch14_02.htm">AudioClip Interface</A><BR>
<A HREF="ch14_03.htm">AppletContext Interface</A><BR>
<A HREF="ch14_04.htm">AppletStub Interface</A><BR>
<A HREF="ch14_05.htm">Audio in Applications</A><BR>

<p>
</DIV>

<P CLASS=para>
Although it is not part of the <tt CLASS=literal>java.awt</tt> 
package, the <tt CLASS=literal>java.applet</tt> package 
is closely related. The <tt CLASS=literal>java.applet</tt> 
package provides support for running an applet in the context of a World 
Wide Web browser. It consists of one class (<tt CLASS=literal>Applet</tt>) 
and three interfaces (<tt CLASS=literal>AppletContext</tt>, 
<tt CLASS=literal>AudioClip</tt>, and <tt CLASS=literal>AppletStub</tt>). 
The <tt CLASS=literal>Applet</tt> class supports the 
"applet life cycle" methods (<tt CLASS=literal>init()</tt>, 
<tt CLASS=literal>start()</tt>, <tt CLASS=literal>stop()</tt>, 
<tt CLASS=literal>destroy()</tt>) that you override 
to write an applet. <tt CLASS=literal>AudioClip</tt> 
provides support for audio within applets. (Applications use the <tt CLASS=literal>sun.audio</tt> 
package for audio support; <tt CLASS=literal>sun.audio</tt> 
is also covered in this chapter.) The <tt CLASS=literal>AppletStub</tt> 
and <tt CLASS=literal>AppletContext</tt> interfaces 
provide a way for the applet to interact with its run-time environment. 
Many of the methods of <tt CLASS=literal>AppletStub</tt> 
and <tt CLASS=literal>AppletContext</tt> are duplicated 
in the <tt CLASS=literal>Applet</tt> class. <A NAME="CH14.APPLET"></A>

<DIV CLASS=sect1>
<h2 CLASS=sect1><A CLASS="TITLE" NAME="JAWT-CH-14-SECT-1">14.1 What's a Java Applet?</A></h2>

<P CLASS=para>
Much of the initial excitement about Java centered around applets. Applets 
are small Java programs that can be embedded within HTML pages and downloaded 
and executed by a web browser. Because executing code from random Internet 
sites presents a security risk, Java goes to great lengths to ensure the 
integrity of the program executing and to prevent it from performing any 
unauthorized tasks. 

<P CLASS=para>
An applet is a specific type of Java <tt CLASS=literal>Container</tt>. 
The class hierarchy of an applet is shown in <A HREF="ch14_01.htm#JAWT-CH-14-FIG-1">Figure 14.1</A>.

<DIV CLASS=figure>
<h4 CLASS=figure><A CLASS="TITLE" NAME="JAWT-CH-14-FIG-1">Figure 14.1: Applet class hierarchy</A></h4>


<p>
<img align=middle src="./figs/jawt1401.gif" alt="[Graphic: Figure 14-1]" width=502 height=257 border=0>

</DIV>

<P CLASS=para>
When you are writing an applet, remember that you can use the features 
of its ancestors. In particular, remember to check the methods of the <tt CLASS=literal>Component</tt>, 
<tt CLASS=literal>Container</tt>, and <tt CLASS=literal>Panel</tt> 
classes, which are inherited by the <tt CLASS=literal>Applet</tt> 
class. 

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JAWT-CH-14-SECT-1.1">Applet Methods</A></h3>

<P CLASS=para>
<A NAME="CH14.NEW"></A>All the methods of <tt CLASS=literal>Applet</tt>, 
except <tt CLASS=literal>setStub()</tt>, either need 
to be overridden or are methods based on one of the <tt CLASS=literal>java.applet</tt> 
interfaces. The system calls <tt CLASS=literal>setStub()</tt> 
to set up the context of the interfaces. The browser implements the <tt CLASS=literal>AppletContext</tt> 
and <tt CLASS=literal>AppletStub</tt> interfaces. Constructor

<P>
<DL CLASS=variablelist>
<DT CLASS=varlistentry><I CLASS=emphasis>public Applet () </I><br>
<DD>

<P CLASS=para>
The system calls the <tt CLASS=literal>Applet</tt> 
constructor when the applet is loaded and before it calls <tt CLASS=literal>setStub()</tt>, 
which sets up the applet's stub and context. When you subclass <tt CLASS=literal>Applet</tt>, 
you usually do not provide a constructor. If you do provide a constructor, 
you do not have access to the <tt CLASS=literal>AppletStub</tt> 
or <tt CLASS=literal>AppletContext</tt> and, therefore, 
may not call any of their methods. </DL>
AppletStub setup

<P>
<DL CLASS=variablelist>
<DT CLASS=varlistentry><I CLASS=emphasis>public final void setStub (AppletStub stub) </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>setStub()</tt> method of <tt CLASS=literal>Applet</tt> 
is called by the browser when the applet is loaded into the system. It 
sets the <tt CLASS=literal>AppletStub</tt> of the 
applet to <tt CLASS=literal>stub</tt>. In turn, the 
<tt CLASS=literal>AppletStub</tt> contains the applet's 
<tt CLASS=literal>AppletContext</tt>. </DL>
Applet information methods

<P CLASS=para>
Several methods of <tt CLASS=literal>Applet</tt> provide 
information that can be used while the applet is running. 

<P>
<DL CLASS=variablelist>
<DT CLASS=varlistentry><I CLASS=emphasis>public AppletContext getAppletContext () </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>getAppletContext()</tt> method 
returns the current <tt CLASS=literal>AppletContext</tt>. 
This is part of the applet's stub, which is set by the system when 
<tt CLASS=literal>setStub()</tt> is called. 

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public URL getCodeBase () </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>getCodeBase()</tt> method returns 
the complete URL of the <I CLASS=emphasis>.class</I> 
file that contains the applet. This method can be used with the <tt CLASS=literal>getImage()</tt> 
or the <tt CLASS=literal>getAudioClip()</tt> methods, described later in this chapter, 
to load an image or audio file relative to the <I CLASS=emphasis>.class</I> 
file location. 

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public URL getDocumentBase () </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>getDocumentBase()</tt> method 
returns the complete URL of the <I CLASS=emphasis>.html</I> 
file that loaded the applet. This can be used with the <tt CLASS=literal>getImage()</tt> 
or <tt CLASS=literal>getAudioClip()</tt> methods, described later in this chapter, 
to load an image or audio file relative to the <I CLASS=emphasis>.html</I> 
file. 

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public String getParameter (String name) </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>getParameter()</tt> method allows 
you to get run-time parameters from within the <tt CLASS=literal>&lt;APPLET&gt;</tt> 
tag of the <I CLASS=emphasis>.html</I> file that 
loaded the applet. Parameters are defined by HTML <tt CLASS=literal>&lt;PARAM&gt;</tt> 
tags, which have the form: 

<DIV CLASS=screen>
<P>
<PRE>
&lt;PARAM name="parameter" value="value&gt;
</PRE>
</DIV>

<P CLASS=para>
If the <tt CLASS=literal>name</tt> parameter of <tt CLASS=literal>getParameter()</tt> 
matches the <tt CLASS=literal>name</tt> string of a <tt CLASS=literal>&lt;PARAM&gt;</tt> 
tag, <tt CLASS=literal>getParameter()</tt> returns 
the tag's <tt CLASS=literal>value</tt> as a string. 
If <tt CLASS=literal>name</tt> is not found within 
the <tt CLASS=literal>&lt;PARAM&gt;</tt> tags of the 
<tt CLASS=literal>&lt;APPLET&gt;</tt>, <tt CLASS=literal>getParameter()</tt> 
returns <tt CLASS=literal>null</tt>. The argument <tt CLASS=literal>name</tt> 
is not case sensitive; that is, it matches parameter names regardless of case. 
Remember that <tt CLASS=literal>getParameter()</tt> 
always returns a string, even 
though the parameter values might appear as integers or floating point 
numbers in the HTML file. In some situations, it makes sense to pass multiple 
values in a single parameter; if you do this, you have to parse the parameter 
string manually. Using a <tt CLASS=literal>StringTokenizer</tt> 
will make the job easier. 

<P CLASS=para>
Enabling your applets to accept parameters allows them to be customized 
at run-time by the HTML author, without providing the source code. This 
provides greater flexibility on the Web without requiring any recoding. 
<A HREF="ch14_01.htm#JAWT-CH-14-EX-1">Example 14.1</A> shows how an applet reads parameters from an HTML 
file. It contains three parts: the HTML file that loads the applet, the 
applet source code, and the output from the applet. 

<DIV CLASS=example>
<h4 CLASS=example><A CLASS="TITLE" NAME="JAWT-CH-14-EX-1">Example 14.1: Getting Parameters from an HTML File</A></h4>

<DIV CLASS=screen>
<P>
<PRE>
&lt;APPLET CODE=ParamApplet WIDTH=100 HEIGHT=100&gt;
&lt;PARAM NAME=one VALUE=1.0&gt;
&lt;PARAM name=TWO value=TOO&gt;
&lt;/APPLET&gt;
public class ParamApplet extends java.applet.Applet {
    public void init () {
        String param;
        float one;
        String two;
        if ((param = getParameter ("ONE")) == null) {
            one = -1.0f;  // Not present
        } else {
            one = Float.valueOf (param).longValue();
        }
        if ((param = getParameter ("two")) == null) {
            two = "two";
        } else {
            two = param.toUpperCase();
        }
        System.out.println ("One: " + one);
        System.out.println ("Two: " + two);
    }
}
One: 1
Two: TOO
</PRE>
</DIV>

</DIV>

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public String getAppletInfo ()  </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>getAppletInfo()</tt> method 
lets an applet provide a short descriptive string to the browser. This 
method is frequently overridden to return a string showing the applet's 
author and copyright information. How (or whether) to display this information 
is up to the browser. With <I CLASS=emphasis>appletviewer</I>, this information is displayed 
when the user selects the Info choice under the Applet 
menu. Neither Netscape Navigator nor Internet Explorer currently display 
this information. 

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public String[][] getParameterInfo ()  </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>getParameterInfo()</tt> method 
lets an applet provide a two-dimensional array of strings describing the 
parameters it reads from <tt CLASS=literal>&lt;PARAM&gt;</tt> 
tags. It returns an array of three strings for each parameter. In each 
array, the first <tt CLASS=literal>String</tt> represents 
the parameter name, the second describes the data type, and the third is 
a brief description or range of values. Like <tt CLASS=literal>getAppletInfo()</tt>, 
how (or whether) to display this information is up to the browser. With 
appletviewer, this information is displayed when the user selects the Info 
choice under the Applet menu. Neither Netscape Navigator nor Internet Explorer 
currently display this information. The following code shows how an applet 
might use <tt CLASS=literal>getParameterInfo()</tt> 
and <tt CLASS=literal>getAppletInfo()</tt>: 

<DIV CLASS=screen>
<P>
<PRE>
public String getAppletInfo() {
    String whoami = "By John Zukowski (c) 1997";
    return whoami;
}
public String[][] getParameterInfo() {
    String[][] strings = {
        {"parameter1",     "String",      "Background Color name"},
        {"parameter2",     "URL",         "Image File"},
        {"parameter3",     "1-10",        "Number in Series"}
    };
    return strings;
}
</PRE>
</DIV>

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public void showStatus (String message) </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>showStatus()</tt> method displays 
<tt CLASS=literal>message</tt> on the browser's 
status line, if it has one. Again, how to display this string is up to 
the browser, and the browser can overwrite it whenever it wants. You should 
only use <tt CLASS=literal>showStatus()</tt> for messages 
that the user can afford to miss. 

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public boolean isActive () </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>isActive()</tt> method returns 
the current state of the applet. While an applet is initializing, it is 
not active, and calls to <tt CLASS=literal>isActive()</tt> 
return <tt CLASS=literal>false</tt>. The system marks the applet active just prior to calling 
<tt CLASS=literal>start()</tt>; after this point, 
calls to <tt CLASS=literal>isActive()</tt> return 
<tt CLASS=literal>true</tt>. 

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public Locale getLocale () <img src="gifs/bstar.gif" alt="(New)" border=0>  </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>getLocale()</tt> method retrieves 
the current <tt CLASS=literal>Locale</tt> of the applet, 
if it has one. Using a <tt CLASS=literal>Locale</tt> 
allows you to write programs that can adapt themselves to different languages 
and different regional variants. If no <tt CLASS=literal>Locale</tt> 
has been set, <tt CLASS=literal>getLocale()</tt> returns 
the default <tt CLASS=literal>Locale</tt>. The default 
<tt CLASS=literal>Locale</tt> has a user language 
of English and no region. To change the default <tt CLASS=literal>Locale</tt>, 
set the system properties <tt CLASS=literal>user.language</tt> 
and <tt CLASS=literal>user.region</tt>, or call <tt CLASS=literal>Locale.setDefault()</tt> 
(<tt CLASS=literal>setDefault()</tt> verifies access 
rights with the security manager).[1] 

<blockquote class=footnote>
<P CLASS=para>[1] 
 
For more on the <tt CLASS=literal>Locale</tt> class, 
see <I CLASS=emphasis>Java Fundamental Classes Reference</I>, by Mark Grand, from O'Reilly &amp; Associates.
</blockquote>
</DL>
Applet life cycle

<P CLASS=para>
The browser calls four methods of the <tt CLASS=literal>Applet</tt> 
class to execute the applet. These methods constitute the applet's 
life cycle. The default versions don't do anything; you must override 
at least one of them to create a useful applet. 

<P>
<DL CLASS=variablelist>
<DT CLASS=varlistentry><I CLASS=emphasis>public void init () </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>init()</tt> method is called 
once when the applet is first loaded. It should be used for tasks that 
need to be done only once. <tt CLASS=literal>init()</tt> 
is often used to load images or sound files, set up the screen, get parameters 
out of the HTML file, and create objects the applet will need later. You 
should not do anything that might "hang" or wait indefinitely. 
In a sense, <tt CLASS=literal>init()</tt> does things 
that might otherwise be done in an applet's constructor. 

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public void start ()   </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>start()</tt> method is called 
every time the browser displays the web page containing the applet. <tt CLASS=literal>start()</tt> 
usually does the "work" of the applet. It often starts threads, 
plays sound files, or does computation. <tt CLASS=literal>start()</tt> 
may also be called when the browser is de-iconified. 

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public void stop () </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>stop()</tt> method is called 
whenever the browser leaves the web page containing the applet. It should 
stop or suspend anything that the applet is doing. For example, it should 
suspend any threads that have been created and stop playing any sound 
files.<tt CLASS=literal> stop()</tt> may also be called 
when the browser is iconified. 

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public void destroy ()   </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>destroy()</tt> method is called 
when the browser determines that it no longer needs to keep the applet 
around--in practice, when the browser decides to remove the applet 
from its cache or the browser exits. After this point, if the browser needs 
to display the applet again, it will reload the applet and call the applet's 
<tt CLASS=literal>init()</tt> method. <tt CLASS=literal>destroy()</tt> 
gives the applet a final opportunity to release any resources it is using 
(for example, close any open sockets). Most applets don't need to 
implement <tt CLASS=literal>destroy()</tt>. It is 
always a good idea to release resources as soon as they aren't needed, 
rather than waiting for <tt CLASS=literal>destroy()</tt>. 
There are no guarantees about when <tt CLASS=literal>destroy()</tt> 
will be called; if your browser has a sufficiently large cache, the applet 
may stay around for a very long time. </DL>
Applet-sizing methods

<P>
<DL CLASS=variablelist>
<DT CLASS=varlistentry><I CLASS=emphasis>public void resize(int width, int height)</I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>resize()</tt> method changes 
the size of the applet space to <tt CLASS=literal>width</tt> 
x <tt CLASS=literal>height</tt>. The browser must 
support changing the applet space or else the sizing does not change. Netscape 
Navigator does not allow an applet to change its size; the applet is sized 
to the region allocated by the <tt CLASS=literal>&lt;APPLET&gt;</tt> 
tag, period. 

<P CLASS=para>
Because <tt CLASS=literal>Applet</tt> is a subclass 
of <tt CLASS=literal>Component</tt>, it inherits the 
Java 1.1 method <tt CLASS=literal>setSize()</tt>, 
which has the same function. 

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public void resize (Dimension dim)</I><br>
<DD>

<P CLASS=para>
This <tt CLASS=literal>resize()</tt> method calls 
the previous version of <tt CLASS=literal>resize()</tt> with a width of <tt CLASS=literal>dim.width</tt> 
and a height of <tt CLASS=literal>dim.height</tt>. </DL>
Images

<P CLASS=para>
We have discussed <tt CLASS=literal>Image</tt> objects extensively in <A HREF="ch02_01.htm">Chapter 2, <i>Simple Graphics</i></A>, and <A HREF="ch12_01.htm">Chapter 12, <i>Image Processing</i></A>, and used them in many of our examples. When writing an applet, you can use the <tt CLASS=literal>getImage()</tt> 
method directly. In applications, you must go through <tt CLASS=literal>Toolkit</tt> 
(which the following methods call) to get images. 

<P>
<DL CLASS=variablelist>
<DT CLASS=varlistentry><I CLASS=emphasis>public Image getImage (URL url) </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>getImage()</tt> method loads 
the image file located at <tt CLASS=literal>url</tt>. <tt CLASS=literal>url</tt> 
must be a complete and valid URL. The method returns a system-specific 
object that subclasses <tt CLASS=literal>Image</tt> 
and returns immediately. The <tt CLASS=literal>Image</tt> 
is not loaded until needed, either by <tt CLASS=literal>prepareImage()</tt>, 
<tt CLASS=literal>MediaTracker</tt>, or <tt CLASS=literal>drawImage()</tt>. 

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public Image getImage (URL url, String filename) </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>getImage()</tt> method loads 
the image file located at <tt CLASS=literal>url</tt> 
in <tt CLASS=literal>filename</tt>. The applet locates 
the file relative to the specified URL; that is, if the URL ends with a filename, 
the applet removes the filename and appends the <tt CLASS=literal>filename</tt> 
argument to produce a new URL. <tt CLASS=literal>getImage()</tt> 
returns a system-specific object that subclasses <tt CLASS=literal>Image</tt> 
and returns immediately. The <tt CLASS=literal>Image</tt> 
is not loaded until needed, either by <tt CLASS=literal>prepareImage()</tt>, 
<tt CLASS=literal>MediaTracker</tt>, or <tt CLASS=literal>drawImage()</tt>. 

<P CLASS=para>
In most cases, the <tt CLASS=literal>url</tt> argument 
is a call to <tt CLASS=literal>getDocumentBase()</tt> 
or <tt CLASS=literal>getCodeBase()</tt>; most often, 
image files are located in the same directory as the HTML file, the applet's 
Java class file, or their own subdirectory. </DL>
Audio

<P CLASS=para>
<A NAME="CH14.AA1"></A><A NAME="CH14.AA2"></A>Every Java platform is guaranteed to understand Sun's AU file format, 
which contains a single channel of 8000 Hz &micro;Law encoded audio data.[2] 
Java applets do not require any helper applications to play audio; they 
use the browser's audio capabilities. You can use an independent 
application, like Sun's <I CLASS=emphasis>audiotool</I>, to control the volume. Of course, 
the user's workstation or PC needs audio hardware, but these days, 
it's hard to buy a computer that isn't equipped for audio. 

<blockquote class=footnote>
<P CLASS=para>[2] 
 
The AU format is explained in the Audio File Format FAQ (version 3.10) 
located at <I CLASS=emphasis>ftp://ftp.cwi.nl/pub/audio/index.html</I> 
in files <I CLASS=emphasis>AudioFormats.part1</I> 
and <I CLASS=emphasis>AudioFormats.part2</I>.
</blockquote>
<P CLASS=para>
The Java Media Framework API is rumored to provide support for additional 
audio formats, like Microsoft's <I CLASS=emphasis>.wav</I> files or Macintosh/SGI 
<I CLASS=emphasis>.aiff</I> audio files. At present, if you want your Java program to play audio 
files in other formats, you must first convert the audio file to the <I CLASS=emphasis>.au</I> 
format, using a utility like SOX (Sound Exchange).[3] 
Once converted, your Java program can play the resulting <I CLASS=emphasis>.au</I> 
file normally. (If you are interested in more information about audio, look in the <I CLASS=emphasis>alt.binaries.sounds.d </I>newsgroup.) 

<blockquote class=footnote>
<P CLASS=para>[3] 
 
SOX is available at <A HREF="http://www.spies.com/Sox">http://www.spies.com/Sox</A>. 
The current version of SOX is 10; version 11 is in gamma release. The UNIX 
source is located in <I CLASS=emphasis>sox10.tar.gz</I>&nbsp;, 
while the DOS executable is <I CLASS=emphasis>sox10dos.zip</I>.
</blockquote>
<P CLASS=para>
The <tt CLASS=literal>Applet</tt> class provides two 
ways to play audio clips. The first mechanism provides a method to load 
and play an audio file once: 

<P>
<DL CLASS=variablelist>
<DT CLASS=varlistentry><I CLASS=emphasis>public void play (URL url) </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>play()</tt> method downloads 
and plays the audio file located at <tt CLASS=literal>url</tt>. 
<tt CLASS=literal>url</tt> must be a complete and 
valid URL. If <tt CLASS=literal>url</tt> is invalid, 
no sound is played. Some environments throw an exception if the URL is 
invalid, but not all. Calling <tt CLASS=literal>play()</tt> 
within an applet's <tt CLASS=literal>destroy()</tt> 
method usually has no effect; the applet and its resources will probably 
be deallocated before <tt CLASS=literal>play()</tt> 
has time to download the audio file. 

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public void play (URL url, String filename) </I><br>
<DD>

<P CLASS=para>
This version of <tt CLASS=literal>play()</tt> downloads 
and plays the audio file located at <tt CLASS=literal>url</tt> 
in the file <tt CLASS=literal>filename</tt>. The applet 
locates the file relative to the specified URL; that is, if the URL ends with 
a filename, the applet removes the filename and appends the <tt CLASS=literal>filename</tt> 
argument to produce a new URL. If the resulting URL is invalid, no sound 
is played. Some environments throw an exception if the URL is invalid, but not all. 

<P CLASS=para>
In most cases, the <tt CLASS=literal>url</tt> argument 
is a call to <tt CLASS=literal>getDocumentBase()</tt> 
or <tt CLASS=literal>getCodeBase()</tt>; most often, 
sound files are located in the same directory as the HTML file or the applet's 
Java class file. For some reason, you cannot have a double dot (<tt CLASS=literal>..</tt>) 
in the URL of an audio file; you can in the URL of an image file. Putting a double dot in the URL of an audio file raises a security 
exception in an applet causing <tt CLASS=literal>play()</tt> to fail. 

<P CLASS=para>
The following applet plays an audio file located relative to the HTML file 
from which the applet was loaded: 

<DIV CLASS=screen>
<P>
<PRE>
import java.net.*;
import java.applet.*;
public class audioTest extends Applet {
    public void init () {
        System.out.println ("Before");
        play (getDocumentBase(), "audio/flintstones.au");
        System.out.println ("After");
    }
}
</PRE>
</DIV>

</DL>
<P CLASS=para>
The second way to play audio files splits the process into two steps: you 
get an <tt CLASS=literal>AudioClip</tt> object and 
then play it as necessary. This procedure eliminates a significant drawback 
to <tt CLASS=literal>play()</tt>: if you call <tt CLASS=literal>play()</tt> 
repeatedly, it reloads the audio file each time, making the applet much 
slower. 

<P>
<DL CLASS=variablelist>
<DT CLASS=varlistentry><I CLASS=emphasis>public AudioClip getAudioClip (URL url) </I><br>
<DD>

<P CLASS=para>
The <tt CLASS=literal>getAudioClip()</tt> method loads 
the audio file located at <tt CLASS=literal>url</tt>. 
<tt CLASS=literal>url</tt> must be a complete and 
valid URL. Upon success, <tt CLASS=literal>getAudioClip()</tt> 
returns an instance of a class that implements the <tt CLASS=literal>AudioClip</tt> 
interface. You can then call methods in the <tt CLASS=literal>AudioClip</tt> 
interface (see <A HREF="ch14_02.htm#JAWT-CH-14-SECT-2">AudioClip Interface</A>) to play the clip. If 
an error occurs during loading (e.g., because the file was not found or the URL was invalid), <tt CLASS=literal>getAudioClip()</tt> 
returns <tt CLASS=literal>null</tt>. 

<P CLASS=para>
<tt CLASS=literal>getAudioClip()</tt> sounds similar 
to <tt CLASS=literal>getImage()</tt>, and it is. However, 
Java currently loads audio clips synchronously; it does not start a separate 
thread as it does for images. You may want to create a helper class that 
loads audio clips in a separate thread. 

<P CLASS=para>
The actual class of the <tt CLASS=literal>AudioClip</tt> 
object depends on the platform you are using; you shouldn't need 
to know it. If you are curious, the <I CLASS=emphasis>appletviewer</I> uses the class <tt CLASS=literal>sun.applet.AppletAudioClip</tt>; 
Netscape Navigator uses the class <tt CLASS=literal>netscape.applet.AppletAudioClip</tt>. 

<p>
<DT CLASS=varlistentry><I CLASS=emphasis>public AudioClip getAudioClip (URL url , String filename) </I><br>
<DD>

<P CLASS=para>
This version of the <tt CLASS=literal>getAudioClip()</tt> 
method loads the audio file located at <tt CLASS=literal>url</tt> 
in the file <tt CLASS=literal>filename</tt>. The applet 
locates the file relative to the specified URL; that is, if the URL ends with 
a filename, the applet removes the filename and appends the <tt CLASS=literal>filename</tt> 
argument to produce a new URL. If the resulting URL is invalid, the file 
is not loaded. Upon success, <tt CLASS=literal>getAudioClip()</tt> 
returns an instance of a class that implements the <tt CLASS=literal>AudioClip</tt> 
interface. You can then call methods in the <tt CLASS=literal>AudioClip</tt> 
interface (see <A HREF="ch14_02.htm#JAWT-CH-14-SECT-2">AudioClip Interface</A>) to play the clip. If 
an error occurs during loading (e.g., because the file was not found or the URL was invalid), <tt CLASS=literal>getAudioClip()</tt> 
returns <tt CLASS=literal>null</tt>. 

<P CLASS=para>
In most cases, the <tt CLASS=literal>url</tt> argument 
is a call to <tt CLASS=literal>getDocumentBase()</tt> 
or <tt CLASS=literal>getCodeBase()</tt>; most often, 
sound files are located in the same directory as the HTML file or the applet's 
Java class file. </DL>
</DIV>

</DIV>


<DIV CLASS=htmlnav>

<P>
<HR align=left width=515>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch13_03.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><a href="index.htm"><img src='gifs/txthome.gif' border=0 alt='Home'></a></td>
<td width=172 align=right valign=top><A HREF="ch14_02.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
<tr>
<td width=172 align=left valign=top>AWTError</td>
<td width=171 align=center valign=top><a href="index/idx_a.htm"><img src='gifs/index.gif' alt='Book Index' border=0></a></td>
<td width=172 align=right valign=top>AudioClip Interface</td>
</tr>
</table>
<hr align=left width=515>

<IMG SRC="gifs/smnavbar.gif" USEMAP="#map" BORDER=0> 
<MAP NAME="map"> 
<AREA SHAPE=RECT COORDS="0,0,108,15" HREF="../javanut/index.htm"
alt="Java in a Nutshell"> 
<AREA SHAPE=RECT COORDS="109,0,200,15" HREF="../langref/index.htm" 
alt="Java Language Reference"> 
<AREA SHAPE=RECT COORDS="203,0,290,15" HREF="../awt/index.htm" 
alt="Java AWT"> 
<AREA SHAPE=RECT COORDS="291,0,419,15" HREF="../fclass/index.htm" 
alt="Java Fundamental Classes"> 
<AREA SHAPE=RECT COORDS="421,0,514,15" HREF="../exp/index.htm" 
alt="Exploring Java"> 
</MAP>
</DIV>

</BODY>
</HTML>
